//
//  MSMessageVC.m
//  MS
//
//  Created by He Yuan on 13-2-6.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSMessageVC.h"
#import "EGORefreshTableHeaderView.h"
#import "CustomSegmentedControl.h"

#import "UIButton+WebCache.h"
#import "MSMessageCell.h"

#import "MSChatVC.h"

@interface MSMessageVC ()<CustomSegmentedControlDelegate,EGORefreshTableHeaderDelegate, UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate>
{
    UITableView  *mesTableView;
    
    BOOL _reloading;
    
    EGORefreshTableHeaderView *_refreshHeaderView;    

}

@property(nonatomic,retain)NSMutableArray *dataArr;

@property(nonatomic,retain)UITableView  *mesTableView;

- (void)reloadTableViewDataSource;

- (void)doneLoadingTableViewData;

@end

@implementation MSMessageVC
@synthesize mesTableView = _mesTableView;
@synthesize dataArr = _dataArr;

- (id)init
{
    self = [super init];
    if (self)
    {
        // Custom initialization
        
        _dataArr = [[NSMutableArray alloc]initWithObjects:nil,nil];
//        
//        for (int i = 0 ; i < 15; i++)
//        {
//            NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:
//                                  @"http://www.heyuan110.com/avatar.png",@"avatar",
//                                  @"23",@"fuid",
//                                  @"圆头",@"t_user_name",
//                                  @"2分钟前",@"time",
//                                  @"新年快乐啊",@"message",
//                                  nil];
//            [_dataArr addObject:item];
//        }
    }
    
    return self;
}

-(void)loadView
{
    [super loadView];

    _mesTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _mesTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _mesTableView.delegate = self;
    _mesTableView.dataSource = self;
    _mesTableView.backgroundColor = [UIColor clearColor];
    _mesTableView.backgroundView = nil;
    [self.view addSubview:_mesTableView];
    
    
    //custom segment
    NSDictionary *item1 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"私信"),@"title",@"s1",@"img", nil];
    //    NSDictionary *item2 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"通知"),@"title",@"s2",@"img", nil];
    NSDictionary *item3 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"通知"),@"title",@"s3",@"img", nil];
    NSArray *items = [NSArray arrayWithObjects:item1,item3, nil];
    CustomSegmentedControl *segment = [[CustomSegmentedControl alloc]initWithFrame:CGRectZero items:items defaultSelectIndex:0];
    segment.delegate = self;
    self.navigationItem.titleView=segment;
    
    if (_refreshHeaderView == nil)
    {
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.mesTableView.bounds.size.height, self.view.frame.size.width, self.mesTableView.bounds.size.height)];
		_refreshHeaderView.delegate = self;
		[self.mesTableView addSubview:_refreshHeaderView];
	}

	[_refreshHeaderView refreshLastUpdatedDate];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:NO];
}

- (void)viewDidLoad
{
    [self setTitle:@"消息" showBackButton:NO];

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
    
    [self performSelector:@selector(ViewFrashData) withObject:nil afterDelay:0.6];
}

-(void)ViewFrashData
{
    [_mesTableView setContentOffset:CGPointMake(0,-75) animated:YES];
    [self performSelector:@selector(doneManualRefresh) withObject:nil afterDelay:0.4];
}

-(void)doneManualRefresh
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self.mesTableView];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.mesTableView];
}

-(void)requestMessage
{
    [WebService  getRequestAction:APIPrivateMessage
                            param:[NSDictionary dictionaryWithObjectsAndKeys:[[MSSetting sharedSetting]getAccountID],@"uid", nil]
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             [_dataArr removeAllObjects];
             NSArray *messages = (NSArray *)info;
             [_dataArr addObjectsFromArray:messages];
             [self.mesTableView reloadData];
             HYLog(@"%@",info);
         }
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
     } progress:self.navigationController.view];
}


#pragma CustomSegmentedControlDelegate methord
-(void)didSelectIndex:(NSUInteger)selectedIndex withSegmentControl:(CustomSegmentedControl*)segmentControl
{
//    HYLog(@"%d",selectedIndex);
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource
{	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
    [self requestMessage];
    HYLog(@"start request。。。");
}

- (void)doneLoadingTableViewData
{
    HYLog(@"finish refresh...");
	//  model should call this when its done loading
	_reloading = NO;
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setValue:date forKey:@"EGORefreshTableView_MSMessage_LastRefresh"];
    [[NSUserDefaults standardUserDefaults] synchronize];
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.mesTableView];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{	
   NSDate *date =  [[NSUserDefaults standardUserDefaults] valueForKey:@"EGORefreshTableView_MSMessage_LastRefresh"];
    if (date == nil)date = [NSDate date];
	return date; // should return date data source was last changed

}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArr count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";    
    MSMessageCell *cell = (MSMessageCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[MSMessageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    [cell.iconButton setImageWithURL:[NSURL URLWithString:[item objectForKey:@"avatar"]] forState:UIControlStateNormal];
    id obj = [item objectForKey:@"fuid"];
    NSString *fuid = @"";
    if ([obj isKindOfClass:[NSString class]])
    {
        fuid = obj;
    }
    else
    {
        fuid = [obj stringValue];
    }

    cell.aliasTipLable.text = HYLocalizedString(@"发给:");

    if ([fuid isEqualToString:[[MSSetting sharedSetting]getAccountID]]) {
        cell.aliasTipLable.text = HYLocalizedString(@"发给:");
    }
    else
    {
        cell.aliasTipLable.text = HYLocalizedString(@"来自:");
    }
    cell.aliasLable.text = [item objectForKey:@"t_user_name"];
    cell.timeLbl.text =  [item objectForKey:@"time"];
    [cell.contentLbl setText:[item objectForKey:@"message"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    MSChatVC *vc = [[MSChatVC alloc]initWithInfo:item];
    [vc setHidesBottomBarWhenPushed:YES];
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:YES];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidUnload {
	_refreshHeaderView=nil;
    self.mesTableView = nil;
}

- (void)dealloc
{
    self.mesTableView = nil;
	_refreshHeaderView = nil;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
